
import Singleton from "../../framework/bo/Singleton";
import ConfigGame from "../global/ConfigGame";
import SocketManager from "../../framework/net/SocketManager";
import { NetManagerState, SocketType } from "../../Enum/NetEnums";
import ClientContext from "../global/ClientContext";
import { Util } from "../../framework/utils/util";
import BaseSocket from "../../framework/net/BaseSocket";
import ConnectedData from "../../framework/net/ConnectedData";
import { UIManager } from "../../framework/manager/uiManager";
import { AccountService } from "./service/AccountService";
import { Constant } from "../../Enum/Enum";
import { ClientEvent } from "../../framework/bo/ClientEvent";

export default class LogicBoot extends Singleton {

    private socketManager: SocketManager = null;
    private socket: BaseSocket = null;

    public static get Instance(): LogicBoot {
        return super.GetInstance<LogicBoot>();
    }
    clear() {
        this.socketManager = null;
        this.socket = null;
    }
    /**
     * 逻辑启动程序初始化 需要一个连接大厅的socket
     */
    async init() {
        console.log("logic初始化，连接，然后调用用户登陆或者判断注册");
        this.socketManager = new SocketManager();
        ClientContext.Instance.hallSocketManager = this.socketManager;
        await this.connect();
    }

    async connect() {// TODO while持续连接 此为connect login之后改写到accountServer内部
        for (let i = 0; i < ConfigGame.logicIp.length; ++i) {
            const res: number = await this.connect0(ConfigGame.logicIp[i]);
            if (res != 0) {
                break;
            }
            console.log("服务器重新连接：", i);
        }
        if (this.socketManager.stateNet != NetManagerState.connected) {
            UIManager.instance.showTips(Constant.Tips.TIPS_4);
        } else {// 连接服务器成功
            await AccountService.Instance.getServerInfos();
            UIManager.instance.showTips(Constant.Tips.connected_6,null,Constant.TIPS_ANI_NAME.tips2aniTop);
        }
    }

    async connect0(ip:string): Promise<number> {// 单次连接游戏大厅
        console.log("准备连接逻辑服务器");
        this.socket = this.socketManager.createSocket(ip, ConfigGame.websocketPort, SocketType.logic);
        ClientContext.Instance.hallSocket = this.socket;
        const res: ConnectedData = await this.socketManager.connectSync();// 连接到服务器
        if (res.isSuccess) {
            console.log("连接成功", res.isSuccess);
            return 1;
        } else {
            console.log("连接失败", res.isSuccess);
            return 0;

        }
    }
}